package com.leyou.upload.service.Impl;

import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.leyou.upload.service.UploadService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;


@Service
public class UploadServiceimpl implements UploadService {

    private static final Logger logger = LoggerFactory.getLogger(UploadServiceimpl.class);

    // 支持的文件类型
    private static final List<String> suffixes = Arrays.asList("image/png","image/jpeg");

    @Autowired
    private FastFileStorageClient fastFileStorageClient;

    @Override
    public String uploadimage(MultipartFile file) {

        try {
            String type = file.getContentType();
            if(!"image/png".equals(type)){
                logger.info("上传图片类型不匹配:{}",type);
                return null;
            }

            BufferedImage image = ImageIO.read(file.getInputStream());
            if(image == null){
                logger.info("上传图片内容不符合");
                return null;
            }

            // 2、将图片上传到FastDFS
            // 2.1、获取文件后缀名
            String extension = StringUtils.substringAfterLast(file.getOriginalFilename(), ".");
            // 2.2、上传
            StorePath storePath = this.fastFileStorageClient.uploadFile(file.getInputStream(), file.getSize(), extension, null);
            // 2.3、返回完整路径
            return "http://image.leyou.com/" + storePath.getFullPath();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}